<template>
  <div>
    <el-form>
      <el-row type="flex" justify="end">
        <el-col :span="8" v-if="!autoFresh">
          <el-form-item  style="float: right;margin-right: 10px;">
            <el-dropdown>
              <el-button type="text">
                <i class="el-icon-time"/>
                {{timeRangeTitle}}
                <i class="el-icon-arrow-down"/>
              </el-button>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item @click.native="changeTimeRange('h')">最近一小时</el-dropdown-item>
                <el-dropdown-item @click.native="changeTimeRange('d')">最近一天</el-dropdown-item>
                <el-dropdown-item @click.native="changeTimeRange('w')">最近一周</el-dropdown-item>
                <el-dropdown-item @click.native="changeTimeRange('a')">自定义时间</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-date-picker v-if="timeType==='a'" size="mini"
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="getHostMetrics"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3" v-if="!autoFresh">
          <el-form-item label="统计周期:">
            <el-radio-group v-model="refreshRate" size="mini" border @change="getHostMetrics">
              <el-radio-button label="1m">每分</el-radio-button>
              <el-radio-button label="2s">每秒</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="autoFresh">
          <el-form-item label="更新时间:">
            <span>{{freshTime}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="自动刷新:">
            <el-switch v-model="autoFresh"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs tab-position="right" v-model="activeTab" @tab-click="getHostMetrics">
      <el-tab-pane label="主机性能" name="performance" lazy>
          <el-row :gutter="24">
            <el-col :span="12">
              <line-chart :chart-data="hostLoadData"
                          char-title="Linux 系统负载"
                          :title-tips="['load1: 过去1分钟系统平均负载','load5: 过去5分钟系统平均负载','load15: 过去15分钟系统平均负载']"
                          class-name="chart-border"/>
            </el-col>
            <el-col :span="12">
              <line-chart :chart-data="hostCpuData"
                          char-title="CPU 使用率"
                          :title-tips="['CPU 使用率']"
                          class-name="chart-border"/>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <line-chart :chart-data="hostIopsData"
                          char-title="IOPS"
                          :title-tips="['平均每秒 IO 次数','read: 每秒读次数','write: 每秒写次数']"
                          class-name="chart-border"/>
            </el-col>
            <el-col :span="12">
              <line-chart :chart-data="hostIoCostData"
                          char-title="IO 耗时"
                          :title-tips="['平均每次 IO 耗时','read: 每秒读取平均耗时','write: 每秒写入平均耗时']"
                          class-name="chart-border"/>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <line-chart :chart-data="hostIoVolData"
                          char-title="IO 吞吐量"
                          :title-tips="['平均每秒 IO 数据量','read: 每次读取数据量','write: 每次写入数据量']"
                          class-name="chart-border"/>
            </el-col>
            <el-col :span="12">
              <line-chart :chart-data="hostNetData"
                          char-title="网络吞吐率"
                          :title-tips="['网络吞吐率','receive: 每秒接收数据量','send: 每秒发送数据量']"
                          class-name="chart-border"/>
            </el-col>
          </el-row>
      </el-tab-pane>
      <el-tab-pane label="主机资源" name="resource" lazy>
        <el-row :gutter="24">
          <el-col :span="12">
            <line-chart :chart-data="hostMemoryData"
                        char-title="内存"
                        :title-tips="['used: 已使用物理内存大小','buffers: 内核 Buffer Cache 大小',
                        'free: 可用物理内存大小','cached: 缓存使用的内存']"
                        class-name="chart-border"/>
          </el-col>
          <el-col :span="12">
            <line-chart :chart-data="hostDiskData"
                        char-title="磁盘"
                        :title-tips="['磁盘使用率']"
                        class-name="chart-border"/>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getLineMetrics } from "@/api/machine/metrics";
import LineChart from '@/views/dashboard/LineChart'
import {parseTime} from "@/utils/ruoyi";
export default {
  name: "MachineMonitor",
  props:["machineIp"],
  components:{
    LineChart
  },
  data() {
    return {
      autoFresh:false,
      refreshRate:"1m",
      freshTime:null,
      timeRange:[],
      timeType:"h",
      activeTab:"performance",
      hostLoadData:{},
      hostCpuData:{},
      hostIopsData:{},
      hostIoCostData:{},
      hostIoVolData:{},
      hostNetData:{},
      hostMemoryData:{},
      hostDiskData:{},
      metricsInterval:undefined,
    };
  },
  created() {
    this.getHostMetrics();
  },
  computed:{
    timeRangeTitle(){
      if(this.timeType==='h')
          return "最近一小时";
      if(this.timeType==='d')
          return "最近一天";
      if(this.timeType==='w')
          return "最近一周";
      if(this.timeType==='a')
          return "自定义时间";
      return "最近一小时";
    }
  },
  watch:{
    autoFresh:{
      handler(val){
        this.autoFreshMetrics();
      }
    },
  },
  methods: {
    changeTimeRange(range){
      this.timeType = range;
      this.getHostMetrics();
    },
    autoFreshMetrics(){
      this.getHostMetrics();
      if(this.autoFresh){
        this.freshTime = parseTime(new Date().getTime(),'{y}年{m}月{d}日 {h}:{i}:{s}');
        this.metricsInterval = setTimeout(this.autoFreshMetrics,1000);
      }else{
        this.destroyInterval();
      }
    },
    getHostMetrics(){
      if(this.timeType==='a'&&this.timeRange.length!=2){
        return;
      }
      let params = {
          query:"node_load",
          timeRange:this.autoFresh?"mi":this.timeType,
          labels:{
            "host_ip":this.machineIp,
            interval:this.autoFresh?"2s":this.refreshRate
          }
      };
      if(this.timeType==='a'){
          params['start']=Math.floor(this.timeRange[0].getTime() / 1000);
          params['end']=Math.floor(this.timeRange[1].getTime() / 1000);
      }
      //主机性能
      if(this.activeTab==='performance'){
        this.getHostMetricsData(params,(data =>{this.hostLoadData = data;}));
        params.query="node_cpu";
        this.getHostMetricsData(params,(data =>{this.hostCpuData = data;}));
        params.query="node_iops";
        this.getHostMetricsData(params,(data =>{this.hostIopsData = data;}));
        params.query="node_iocost";
        this.getHostMetricsData(params,(data =>{this.hostIoCostData = data;}));
        params.query="node_iovol";
        this.getHostMetricsData(params,(data =>{this.hostIoVolData = data;}));
        params.query="node_network";
        this.getHostMetricsData(params,(data =>{this.hostNetData = data;}));
      }
      //主机资源
      if(this.activeTab==='resource'){
        params.query="node_memory";
        this.getHostMetricsData(params,(data =>{this.hostMemoryData = data;}));
        params.query="node_disk";
        this.getHostMetricsData(params,(data =>{this.hostDiskData = data;}));
      }
    },
    getHostMetricsData(params,callback){
      getLineMetrics(params).then(res=>{
          if(res.data){
            callback(this.buildLineData(res.data));
          }
      }).catch(err=>{
        console.log(err)
      });
    },
    buildLineData(data){
       let seriesData=[];
       let xAxisData=[];
       Object.keys(data).forEach(metric =>{
          if(data[metric].result.length>0){
              data[metric].result.forEach(label_metrics=>{
                  let series = {name:metric,type:"line",symbol:'none',data:[]};
                  if(label_metrics.metric.metric_name){
                     series.name=label_metrics.metric.metric_name;
                  }
                  label_metrics.values.forEach(value =>{
                    if(!xAxisData.includes(value[0])){
                      xAxisData.push(value[0])
                    }
                    series.data.push(parseFloat(value[1]).toFixed(2));
                  })
                  seriesData.push(series);
              })
              /*data[metric].result[0].values.forEach(value =>{
                if(!xAxisData.includes(value[0])){
                  xAxisData.push(value[0])
                }
                series.data.push(parseFloat(value[1]).toFixed(2));
              })*/
          }
       })
      return {xAxisData:xAxisData,seriesData:seriesData};
    },
    backTo(){
      this.$router.push("/machine");
    },
    destroyInterval(){
      if(this.metricsInterval){
        clearTimeout(this.metricsInterval)
      }
    },
  },
  destroyed() {
      this.destroyInterval();
  },
};
</script>
